using Microsoft.Xna.Framework.Input.Touch;
using ProtectThePieWP7.GeneralClasses;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using ProtectThePie;
using Microsoft.Xna.Framework.Audio;
using ThreeThingGame;

namespace ProtectThePieWP7.AdditionalClasses
{
    public class SoundLever : Lever
    {
        private bool soundStateMemory;
        private bool musicStateMemory;
        private SoundEffect clickSound;

        public SoundLever(MySoundEngine soundEngine, Rectangle rectangle, Texture2D texture, SoundEffect clickSound)
        {
            this.rectangle = rectangle;
            this.clickSound = clickSound;
            position = new Vector2(rectangle.X, rectangle.Y);
            sprite = new Sprite(texture, new Vector2(rectangle.X, rectangle.Y), rectangle.Width / 2, 2);
            sprite.AddTexel((int)LeverState.on, (int)LeverState.on, 1);
            sprite.AddTexel((int)LeverState.off, (int)LeverState.off, 1);
            sprite.Update(-1.57f);
            Switch(soundEngine);

            soundStateMemory = true;
            musicStateMemory = true;
        }

        public void Update(TouchCollection touches, ref MySoundEngine soundEngine)
        {           
            foreach (TouchLocation tl in touches)
            {
                if (Vector2.Distance(tl.Position, position) < 50)
                {
                    switch (tl.State)
                    {
                        case TouchLocationState.Pressed:
                            Game1.soundEngine.PlaySoundEffect(clickSound);
                            break;
                        case TouchLocationState.Released:
                            if (state == LeverState.on)
                            {
                                saveStatesToMemory(ref soundEngine);

                                soundEngine.TurnSoundOff();
                                soundEngine.TurnMusicOff();
                            }
                            else
                            {
                                restoreStateFromMemory(ref soundEngine);
                            }
                            break;
                    }
                }
            }

            Switch(soundEngine);
        }

        public void Switch(MySoundEngine soundEngine)
        {
            if (soundEngine.IsMusicOn() || soundEngine.IsSoundOn()) state = LeverState.on;
            else state = LeverState.off;
        }

        private void saveStatesToMemory(ref MySoundEngine soundEngine)
        {
            soundStateMemory = soundEngine.IsSoundOn();
            musicStateMemory = soundEngine.IsMusicOn();
        }

        private void restoreStateFromMemory(ref MySoundEngine soundEngine)
        {
            if (soundStateMemory) soundEngine.TurnSoundOn();
            if (musicStateMemory) soundEngine.TurnMusicOn();
        }
    }
}
